package com.atguigu.gmall.user.controller;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.gmall.common.constant.RedisConst;
import com.atguigu.gmall.common.result.Result;
import com.atguigu.gmall.common.util.IpUtil;
import com.atguigu.gmall.model.user.UserInfo;
import com.atguigu.gmall.user.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/api/user/passport")
public class PassportApiController {
    @Autowired
    private UserService userService;
    @Autowired
    private RedisTemplate redisTemplate;

    @PostMapping("login")
    public Result login(@RequestBody UserInfo userInfo, HttpServletRequest request) {
        System.out.println("进入到控制器");
        UserInfo info = userService.login(userInfo);
        if (info != null) {
            //生成token并放入cookie中
            Map<String, Object> map = new HashMap<>();
            String token = UUID.randomUUID().toString();
//            String token = UUID.randomUUID().toString().replaceAll("-", "");
            map.put("nickName", info.getNickName());
            map.put("token", token);

            JSONObject userJson = new JSONObject();//UserInfo继承了BaseEntity 中id属性
            userJson.put("userId", info.getId().toString());//将id转换成string
            userJson.put("ip", IpUtil.getIpAddress(request));
            //放入redis中
            redisTemplate.opsForValue().
                    set(RedisConst.USER_LOGIN_KEY_PREFIX + token, userJson.toJSONString(), RedisConst.USERKEY_TIMEOUT, TimeUnit.SECONDS);
            return Result.ok(map);
        } else {
            return Result.fail("用户名或密码错误");
        }
    }

    //退出登录
//    @GetMapping("logout")
//    public Result logout(HttpServletRequest request) {
//
//        redisTemplate.delete(RedisConst.USER_KEY_PREFIX + request.getHeader("token"));
//
//        return Result.ok();
//    }
    //退出登录删除cookie中的token
    @GetMapping("logout")
    public Result logout(@RequestHeader String token, HttpServletRequest request) {

//        String token ="";
//        token = request.getHeader("token");
        String userKey = RedisConst.USER_LOGIN_KEY_PREFIX + token;


        redisTemplate.delete(userKey);

        return Result.ok();
    }
}
